import store from '@/store'
import router from '@/router'
import nProgress from 'nprogress'
import 'nprogress/nprogress.css'

// 白名单
const writeList = ['/login', '/404']

//  路由守卫
router.beforeEach(async function (to, from, next) {
  //  开启进度条
  nProgress.start()
  //  是否有token
  if (store.getters.token) { // 有token
    if (to.path === '/login') {
      next('/')
    } else {
      if (!store.getters.userId) {
        // actions 中返回的数据是promise
        const { roles } = await store.dispatch('user/getUserInfo')
        const routes = await store.dispatch('permission/filteRoutes', roles.menus)
        router.addRoutes(routes)
        next(to.path)
      } else {
        next()
      }
    }
  } else { // 没有token
    if (writeList.indexOf(to.path) > -1) {
      next()
    } else {
      next('/login')
    }
  }
  //   关闭进度条
  nProgress.done()
})

